package com.cqndt.disaster.device.app.impl;


import com.cqndt.disaster.device.app.AppTabDeviceCheckService;
import com.cqndt.disaster.device.common.util.ExportExcelUtil;
import com.cqndt.disaster.device.common.util.ProcessImg;
import com.cqndt.disaster.device.dao.TabDeviceCheckMapper;
import com.cqndt.disaster.device.dao.app.AppTabDeviceCheckMapper;
import com.cqndt.disaster.device.domain.TabAttachment;
import com.cqndt.disaster.device.domain.TabDevice;
import com.cqndt.disaster.device.domain.TabDeviceCheck;
import com.cqndt.disaster.device.vo.Data;
import com.cqndt.disaster.device.vo.TabDeviceCheckVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Service
public class AppTabDeviceCheckServiceImpl implements AppTabDeviceCheckService {

    @Autowired
    private AppTabDeviceCheckMapper appTabDeviceCheckMapper;

    @Value("${file-ip}")
    private String fileIp;

    @Value("${upload-path}")
    private String uploadPath;

    @Value("${ffmpegPath}")
    private String ffmpegPath;

    @Override
    public List<Map<String,String>> listForDevice(String projectNo, String deviceName) {
        return appTabDeviceCheckMapper.listForDevice(projectNo,deviceName);
    }

    @Override
    public int save(TabDeviceCheck tabDeviceCheck) {
        return appTabDeviceCheckMapper.save(tabDeviceCheck);
    }

    @Override
    public String uploadDeviceCheckImg(MultipartFile file) {
        File cfile = new File(uploadPath+File.separator+"img"+File.separator+"device"+File.separator);
        int i = 0;
        if (!cfile.exists()){
            cfile.mkdirs();
        }

        //获取图片名称
        String fileName = file.getOriginalFilename();
        //取出后缀
        String id = UUID.randomUUID().toString();
        String newFileName = "device/"+ id+fileName.substring(fileName.lastIndexOf("."));
        //存储图片
        try {
            file.transferTo(new File(uploadPath+File.separator+"img"+File.separator+newFileName));
            TabAttachment tabAttachment = new TabAttachment();
            tabAttachment.setId(id);
            tabAttachment.setAttachmentDate(new Date());
            tabAttachment.setAttachmentName(fileName);
            tabAttachment.setAttachmentUrl(newFileName);
            tabAttachment.setAttachmentDesc("巡查图片");
            tabAttachment.setAttachmentType("1");
            appTabDeviceCheckMapper.insertTabAttachmentSelective(tabAttachment);
            /*Map<String,String> mapUrl = new HashMap<>();
            mapUrl.put("type","img");
            mapUrl.put("relativePath",newFileName);
            mapUrl.put("absolutePath",fileIp+File.separator+"img"+File.separator+newFileName);*/
            return newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String[] uploadDeviceCheckVideo(MultipartFile file) {
        File  cfile = new File(uploadPath+File.separator+"video"+File.separator+"device"+File.separator);
        int i = 0;
        if (!cfile.exists()){
            cfile.mkdirs();
        }

        //获取视频名称
        String fileName = file.getOriginalFilename();
        //取出后缀
        String id = UUID.randomUUID().toString();
        String newFileName = "device/"+id+fileName.substring(fileName.lastIndexOf("."));
        //存储视频
        try {
            file.transferTo(new File(uploadPath+File.separator+"video"+File.separator+newFileName));
            TabAttachment tabAttachment = new TabAttachment();
            tabAttachment.setId(id);
            tabAttachment.setAttachmentDate(new Date());
            tabAttachment.setAttachmentName(fileName);
            tabAttachment.setAttachmentUrl(newFileName);
            tabAttachment.setAttachmentDesc("巡查视频");
            tabAttachment.setAttachmentType("2");
            appTabDeviceCheckMapper.insertTabAttachmentSelective(tabAttachment);
            File file1 = new File(uploadPath+File.separator+"video"+File.separator+newFileName);
            ProcessImg.getImg(uploadPath+File.separator+"video"+File.separator+newFileName,ffmpegPath);
            //getVideoPic(file1,uploadPath+File.separator+"video"+File.separator+id+"video.jpg");

            /*Map<String,String> mapUrl = new HashMap<>();
            mapUrl.put("type","video");
            mapUrl.put("relativePath",newFileName);
            mapUrl.put("absolutePath",fileIp+File.separator+"video"+File.separator+newFileName);*/
            //String[] str = {newFileName,fileIp+File.separator+"video"+File.separator+id+"video.jpg"};
            String[] str = {newFileName,fileIp+"/"+"video"+"/"+"device"+"/"+id+".jpg"};
            return str;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<TabDeviceCheckVo> listForDeviceCheck(TabDeviceCheckVo tabDeviceCheckVo) {
        return appTabDeviceCheckMapper.listForDeviceCheck(tabDeviceCheckVo);
    }

    @Override
    public Map<String, String> downloadDeviceCheck(TabDeviceCheckVo tabDeviceCheckVo) {
        String[] rowName = {
                "编号", "设备状态","设备外观","设备现状原因","蓄电池状态","故障原因","后期能否恢复","恢复建议","建议阈值","看管人姓名","看管人电话",
                "主管人姓名","主管人电话","设备质量预评","建设年度","建设厂家","核实人","核实日期","备注",
                "设备编号","现场图片","视频"
        };
        String title = "巡查记录";
        String filePath = uploadPath;
        //List<Map<String,Object>> list = appTabDeviceCheckMapper.downloadList(deviceNo,startDate,endDate);
        List<TabDeviceCheckVo> list = appTabDeviceCheckMapper.listForDeviceCheck(tabDeviceCheckVo);
        List<Object[]> list2 = new ArrayList<>();
        SimpleDateFormat s = new SimpleDateFormat("yyyy/MM/dd");
        for(int i=0;i<list.size();i++){
            Object[] o = new Object[rowName.length];
            o[0] = list.get(i).getId();
            o[1] = list.get(i).getDeviceState();
            o[2] = list.get(i).getDeviceAppearance();
            o[3] = list.get(i).getReason();
            o[4] = list.get(i).getBatteryState();
            o[5] = list.get(i).getFaultReason();
            o[6] = list.get(i).getLaterIsRecover();
            o[7] = list.get(i).getRecoverAdvise();
            o[8] = list.get(i).getAdviseValue();
            o[9] = list.get(i).getGuardName();
            o[10] = list.get(i).getGuardPhone();
            o[11] = list.get(i).getManagerName();
            o[12] = list.get(i).getManagerPhone();
            o[13] = list.get(i).getSbzlypg();
            o[14] = list.get(i).getBuildTime();
            o[15] = list.get(i).getBuildUnit();
            o[16] = list.get(i).getCheckPerson();
            if(list.get(i).getCheckDate() == null){
                o[17] = null;
            }else {
                o[17] = s.format(list.get(i).getCheckDate());
            }
            o[18] = list.get(i).getRemark();
            o[19] = list.get(i).getDeviceNo();
            o[20] = list.get(i).getImgIds();
            o[21] = list.get(i).getVideoIds();
            list2.add(o);
        }
        ExportExcelUtil e = new ExportExcelUtil(title,rowName,list2,filePath);
        //ExportExcelUtilByResponse e = new ExportExcelUtilByResponse(title,rowName,list2,filePath,response);
        try {
            String fileName = e.export();
            Map<String,String> map = new HashMap<>();
            map.put("url",fileIp+File.separator+fileName);
            map.put("fileName",fileName);
            return map;
        }catch (Exception e1){
            e1.printStackTrace();
        }
        return null;
    }

    /**
     * 截取上传视频截图
     * @param video
     * @param picPath
     */
    public  void getVideoPic(File video, String picPath) {
//        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
//        try {
//            ff.start();
//
//            // 截取中间帧图片(具体依实际情况而定)
//            int i = 0;
//            int length = ff.getLengthInFrames();
//            int middleFrame = length / 2;
//            Frame frame = null;
//            while (i < length) {
//                frame = ff.grabFrame();
//                if ((i > middleFrame) && (frame.image != null)) {
//                    break;
//                }
//                i++;
//            }
//
//            // 截取的帧图片
//            Java2DFrameConverter converter = new Java2DFrameConverter();
//            BufferedImage srcImage = converter.getBufferedImage(frame);
//            int srcImageWidth = srcImage.getWidth();
//            int srcImageHeight = srcImage.getHeight();
//
//            // 对截图进行等比例缩放(缩略图)
//            int width = 480;
//            int height = (int) (((double) width / srcImageWidth) * srcImageHeight);
//            BufferedImage thumbnailImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
//            thumbnailImage.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
//
//            File picFile = new File(picPath);
//            ImageIO.write(thumbnailImage, "jpg", picFile);
//
//            ff.stop();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

}
